package com.rs.utils;

import org.springframework.util.StringUtils;
import org.apache.commons.io.IOUtils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpPostUtil {

    public static String httpPost(String urlPattern, String params,
                           Map<String, String> properties, String requestMethod)
            throws Exception {
        String result = null;
        URL url = null;
        try {
            url = new URL(urlPattern);
        } catch (MalformedURLException e1) {
            throw new Exception("构建地址失败！" + urlPattern + "===" + e1.getMessage());
        }
        InputStream inputStream = null;
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 连接超时
            connection.setConnectTimeout(20000);
            // 返回数据超时
            connection.setReadTimeout(20000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod(requestMethod);
            // 设置发送数据的格式
            for (Map.Entry<String, String> entry : properties.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            connection.connect();
            if (StringUtils.hasText(params)) {
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(params.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
                outputStream.close();
            }
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                inputStream = new BufferedInputStream(connection.getInputStream());
            } else {
                inputStream = new BufferedInputStream(connection.getErrorStream());
            }
            result = IOUtils.toString(inputStream, String.valueOf(StandardCharsets.UTF_8));
            result = result.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&#xA;", "\n");
        } catch (IOException e) {
            throw new Exception(urlPattern + "请求失败！" + e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ignored) {
                }
            }
        }
        return result;
    }
}
